package com.shirotest.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.shirotest.utility.JsonUtility;
import com.shirotest.utility.ResponseUtility;

@Controller
public class ShiroController {
	@RequestMapping(value = "/login/login.do")
	public void login(HttpServletRequest request,HttpServletResponse response) {
		ObjectNode loginResult = JsonUtility.crateObjectNode();
		Subject currentUser = SecurityUtils.getSubject();
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		if(!currentUser.isAuthenticated()) {
			try {
				//触发MyShiroRealm的doGetAuthenticationInfo方法
				UsernamePasswordToken token = new UsernamePasswordToken(userName, password); 
				token.setRememberMe(true);
				currentUser.login(token);
				loginResult.put("code", 0);
				loginResult.put("message", "登陆成功");
			}catch(UnknownAccountException e) {
				loginResult.put("code", 1);
				loginResult.put("message", "账号输入错误");
			}catch(IncorrectCredentialsException e) {
				loginResult.put("code", 1);
				loginResult.put("message", "密码输入错误");
			}
		}else {
			loginResult.put("code", 0);
			loginResult.put("message", "登陆成功");
		}
		ResponseUtility.responseJson(response, loginResult.toString());
	}
	
	@RequestMapping(value = "/message/getMessage.do")
	public void getMessage(HttpServletResponse response) {
		ResponseUtility.responseText(response, "这里是getMessage");
	}
	
	@RequiresPermissions(value= {"elevator:view", "onlineMonitoring:view"}, logical=Logical.OR)
	@RequestMapping(value = "/ARole")
    public void ARole(HttpServletResponse response) {
		ResponseUtility.responseText(response, "ARole");
    }
	
	@RequiresPermissions("[123,234]")
	@RequestMapping(value = "/BRole")
    public void BRole(HttpServletResponse response) {
		ResponseUtility.responseText(response, "BRole");
    }
	
	
	@RequestMapping(value = "/PRole")
    public void PRole(HttpServletResponse response) {
		ResponseUtility.responseText(response, "PRole");
    }
	
	
	@RequestMapping(value = "/shiro/error.do")
    public void errorPage(HttpServletResponse response) {
		ResponseUtility.sendRedirect(response, "https://www.baidu.com");
    }
}
